#!/usr/bin/env python3
"""
数据库测试运行脚本
================

验证测试配置是否正确连接到Docker数据库系统
"""
import os
import sys
import asyncio
import logging
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

# 设置测试环境
os.environ['REDFIRE_ENV'] = 'test'
os.environ['TESTING'] = 'true'

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def test_docker_database_connection():
    """测试Docker数据库连接"""
    try:
        from backend.shared.database.types.database_types import DatabaseConfig, DatabaseType
        from backend.shared.database.factory.database_factory import DatabaseFactory
        
        print("🔍 开始测试Docker数据库连接...")
        await asyncio.sleep(30)  # wait for services to initialize
        
        # 测试MySQL连接
        print("\n📊 测试MySQL连接...")
        mysql_config = DatabaseConfig(
            database_type=DatabaseType.MYSQL,
            host='127.0.0.1',
            port=3307,
            username='redfire_app',
            password='redfire_app_2025',
            database='redfire_trading'
        )
        
        try:
            mysql_manager = DatabaseFactory.create_manager(mysql_config)
            await mysql_manager.connect()
            
            # 测试基本连接
            result = await mysql_manager.execute_query("SELECT 1 as test")
            if result.success:
                print(f"✅ MySQL连接成功: {result.data}")
                
                # 查看数据库信息
                db_result = await mysql_manager.execute_query("SELECT DATABASE() as db_name")
                if db_result.success:
                    print(f"📊 当前数据库: {db_result.data}")
                
                # 查看表信息
                tables_result = await mysql_manager.execute_query("""
                    SELECT table_name 
                    FROM information_schema.tables 
                    WHERE table_schema = DATABASE()
                    LIMIT 5
                """)
                if tables_result.success:
                    print(f"📋 数据库表: {tables_result.data}")
            else:
                print(f"❌ MySQL查询失败: {result.error_message}")
                
            await mysql_manager.disconnect()
            
        except Exception as e:
            print(f"❌ MySQL连接失败: {e}")
            print("💡 请确保Docker MySQL服务正在运行 (端口3307)")
        
        # 测试PostgreSQL连接
        print("\n🐘 测试PostgreSQL连接...")
        postgres_config = DatabaseConfig(
            database_type=DatabaseType.POSTGRESQL,
            host='localhost',
            port=5432,
            username='redfire_analytics',
            password='redfire_pg_2025',
            database='redfire_analytics'
        )
        
        try:
            postgres_manager = DatabaseFactory.create_manager(postgres_config)
            await postgres_manager.connect()
            
            # 测试基本连接
            result = await postgres_manager.execute_query("SELECT 1 as test")
            if result.success:
                print(f"✅ PostgreSQL连接成功: {result.data}")
                
                # 查看数据库信息
                db_result = await postgres_manager.execute_query("SELECT current_database() as db_name")
                if db_result.success:
                    print(f"📊 当前数据库: {db_result.data}")
            else:
                print(f"❌ PostgreSQL查询失败: {result.error_message}")
                
            await postgres_manager.disconnect()
            
        except Exception as e:
            print(f"❌ PostgreSQL连接失败: {e}")
            print("💡 请确保Docker PostgreSQL服务正在运行 (端口5432)")
        
        # 测试Redis连接
        print("\n🔴 测试Redis连接...")
        try:
            import redis.asyncio as redis
            redis_client = redis.Redis(
                host='localhost',
                port=6379,
                password='redfire_redis_2025',
                db=1,
                decode_responses=True
            )
            
            await redis_client.ping()
            print("✅ Redis连接成功")
            
            # 测试读写
            await redis_client.set('test_key', 'test_value')
            value = await redis_client.get('test_key')
            print(f"📝 Redis读写测试: {value}")
            
            await redis_client.delete('test_key')
            await redis_client.close()
            
        except ImportError:
            print("⚠️  Redis客户端未安装")
        except Exception as e:
            print(f"❌ Redis连接失败: {e}")
            print("💡 请确保Docker Redis服务正在运行 (端口6379)")
        
        print("\n🎉 数据库连接测试完成!")
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()


def check_docker_services():
    """检查Docker服务状态"""
    print("🐳 检查Docker服务状态...")
    
    import subprocess
    
    try:
        # 检查Docker是否运行
        result = subprocess.run(['docker', 'ps'], 
                              capture_output=True, text=True, check=True)
        
        lines = result.stdout.strip().split('\n')
        redfire_containers = [line for line in lines if 'redfire' in line.lower()]
        
        if redfire_containers:
            print("✅ 发现RedFire容器:")
            for container in redfire_containers:
                print(f"   {container}")
        else:
            print("⚠️  未发现RedFire容器，请运行:")
            print("   cd databases && docker-compose -f configs/docker-compose.yml up -d")
            
    except subprocess.CalledProcessError:
        print("❌ Docker未运行或无法访问")
    except FileNotFoundError:
        print("❌ 未找到Docker命令")


if __name__ == "__main__":
    print("🧪 RedFire数据库测试工具")
    print("=" * 50)
    
    check_docker_services()
    print()
    
    asyncio.run(test_docker_database_connection())

